/*
 *  Copyright 2011 Alexey Andreev.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.xthl.core;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.nop.core.Application;
import org.nop.core.ApplicationHandler;
import org.nop.sql.CloseableDataManager;
import org.nop.sql.DataManagerFactory;
import org.nop.sql.DataResult;
import org.nop.sql.QueryBuilder;
import org.nop.util.Injected;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xthl.core.data.PermissionSource;
import org.xthl.core.data.UserPermissionSource;
import org.xthl.core.data.UserSource;

/**
 *
 * @author Alexey Andreev
 */
public class UsersFeatureImpl implements UsersFeature {
    private static final Logger logger = LoggerFactory.getLogger(UsersFeatureImpl.class);
    private Application app;
    private Set<String> permissionNames = new HashSet<String>();

    @Injected
    public UsersFeatureImpl(Application app) {
        this.app = app;
        permissionNames.add("user.admin");
        app.addApplicationHandler(new ApplicationHandler() {
            @Override
            public void started() {
                start();
            }
        });
    }

    @Override
    public void registerPermission(String permission) {
        if (!app.isLoading()) {
            throw new IllegalStateException("Application already loaded");
        }
        if (permissionNames.add(permission)) {
            logger.info("Permission " + permission + " registered");
        }
    }
    
    private void start() {
        CloseableDataManager dataManager = app.get(DataManagerFactory.class).createDataManager();
        try {
            logger.info("Creating permissions");
            QueryBuilder qb = dataManager.getQueryBuilder();
            PermissionSource perm = qb.get(PermissionSource.class);
            UserSource user = qb.get(UserSource.class);
            UserPermissionSource userPerm = qb.get(UserPermissionSource.class);
            
            List<String> permissionList = new ArrayList<String>(permissionNames);
            int batchSize = 100;
            for (int i = 0; i < permissionList.size(); i += batchSize) {
                int top = Math.min(i + batchSize, permissionList.size());
                Set<String> batch = new HashSet<String>(permissionList.subList(i, top));
                DataResult result = dataManager.exec(qb.with(perm)
                        .filter(perm.name().inStrings(batch))
                        .fetch(perm.name()));
                while (result.next()) {
                    batch.remove(result.getString(1));
                }
                for (String name : batch) {
                    dataManager.exec(qb.insertInto(perm)
                            .field(perm.name(), name));
                }
            }
            
            logger.info("Trying to create admin user");
            boolean adminExists = dataManager.exec(qb.with(user)
                    .filter(user.id().eq(1))
                    .fetch(user.id())).next();
            if (!adminExists) {
                dataManager.exec(qb.insertInto(user)
                        .field(user.id(), 1)
                        .field(user.login(), "admin")
                        .field(user.passwordHash(), "30331E2A1D48524B660F3E140A14357B0C4D5769")
                        .field(user.creationDate(), new Date())
                        .field(user.activated(), true));
                dataManager.exec(qb.with(perm)
                        .filter(perm.name().eq("user.admin"))
                        .insertInto(userPerm)
                        .field(userPerm.userId(), qb.wrap(1))
                        .field(userPerm.permissionId(), perm.id()));
            }
            
            dataManager.commit();
        } finally {
            dataManager.close();
        }
    }
}
